package com.xiaobaibai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobaibai.entity.Category;
import com.xiaobaibai.entity.Product;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.ICategoryService;
import com.xiaobaibai.service.IProductService;
import com.xiaobaibai.valid.AddGroup;
import com.xiaobaibai.valid.UpdateGroup;
import com.xiaobaibai.vo.CategoryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "分类管理相关接口")
@RequestMapping("/category")
@CrossOrigin
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IProductService productService;

    @GetMapping("/list")
    @ApiOperation("获取所有类别")
    public ResponseFormat getCategoryList(){
        return ResponseFormat.ok("获取分类成功",getList());
    }

    @GetMapping("/list2")
    @ApiOperation("获取所有类别(适配商品页面的Cascader级联选择器)")
    public ResponseFormat getCategoryList2(){
        List<CategoryVo> list = getList2();
        return ResponseFormat.ok("获取分类成功",list);
    }

    private List<Category> getList(){
        //汇集所有的分类
        //1.用Map汇集子分类->k:pId v:this
        //2.用List接收母分类
        List<Category> list = categoryService.list();

        List<Category> parentList=new ArrayList<>();
        Map<Integer,List<Category>> map=new HashMap<>();
        list.forEach(c->{
            if(c.getCategoryPId().equals(0))
                parentList.add(c);
            else{
                Integer pId=c.getCategoryPId();
                if(map.containsKey(pId)){
                    //存在就加入
                    map.get(pId).add(c);
                }else{
                    //不存在就创建
                    List<Category> categoryList=new ArrayList<>();
                    categoryList.add(c);
                    map.put(pId,categoryList);
                }
            }
        });

        for (Category category : parentList) {
            category.setChildList(map.get(category.getId()));
        }

        return parentList;
    }

    private List<CategoryVo> getList2(){
        //汇集所有的分类
        //1.用Map汇集子分类->k:pId v:this
        //2.用List接收母分类
        QueryWrapper<Category> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("id","category_name","category_p_id");
        List<Category> list = categoryService.list(queryWrapper);

        List<CategoryVo> parentList=new ArrayList<>();
        Map<Integer,List<CategoryVo>> map=new HashMap<>();
        list.forEach(c->{
            if(c.getCategoryPId().equals(0)) {
                CategoryVo categoryVo = new CategoryVo();
                BeanUtils.copyProperties(c,categoryVo);
                parentList.add(categoryVo);
            }
            else{
                Integer pId=c.getCategoryPId();
                if(map.containsKey(pId)){
                    //存在就加入
                    CategoryVo categoryVo = new CategoryVo();
                    BeanUtils.copyProperties(c,categoryVo);
                    map.get(pId).add(categoryVo);
                }else{
                    //不存在就创建
                    List<CategoryVo> categoryList=new ArrayList<>();
                    CategoryVo categoryVo = new CategoryVo();
                    BeanUtils.copyProperties(c,categoryVo);
                    categoryList.add(categoryVo);
                    map.put(pId,categoryList);
                }
            }
        });

        for (CategoryVo categoryVo : parentList) {
            categoryVo.setChildList(map.get(categoryVo.getId()));
        }

        return parentList;
    }

    @PostMapping("/do-category")
    @ApiOperation("增加类别")
    @CacheEvict(value = "category",allEntries = true)
    public ResponseFormat addCategory(@RequestBody @Validated(value = AddGroup.class)
                                              Category category){
        boolean flag = categoryService.save(category);
        if(!flag)
            return ResponseFormat.failure("添加分类失败");
        return ResponseFormat.ok("添加分类成功",category);
    }

    @PutMapping("/do-category")
    @ApiOperation("修改类别")
    @CacheEvict(value = "category",allEntries = true)
    public ResponseFormat updateCategory(@RequestBody @Validated(value = UpdateGroup.class)
                                                     Category category){
        boolean flag = categoryService.updateById(category);
        if(!flag)
            return ResponseFormat.failure("修改分类失败");
        return ResponseFormat.ok("修改分类成功",category);
    }

    @DeleteMapping("/do-category")
    @ApiOperation("删除类别")
    @CacheEvict(value = "category",allEntries = true)
    public ResponseFormat deleteCategory(@RequestParam(value = "id")String id){
        //查询此分类下是否还有分类+此分类下是否有商品
        boolean flag = categoryService.haveChild(Integer.parseInt(id));
        if(flag)
            return ResponseFormat.failure("此分类下有子分类,不可删除");
        QueryWrapper<Product> queryWrapperProduct=new QueryWrapper<>();
        queryWrapperProduct.eq("category_id",id);
        flag = productService.haveProductByCategoryId(Integer.parseInt(id));
        if(flag)
            return ResponseFormat.failure("此分类下有商品,不可删除");
        categoryService.removeById(id);
        return ResponseFormat.ok("删除成功");
    }

}
